from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SKUImage, SKU, GoodsCategory, SPU
from meiduo_admin.utils.page import PageNum
from meiduo_admin.serialziers.skus import SKUSerializer, GoodsCategorySerializer, SPUSpecSerializer


class SKUView(ModelViewSet):
    """
    sku views
    """

    # 权限指定
    # permission_classes = [IsAdminUser, ]
    # 图片查询集
    queryset = SKU.objects.all()
    # 图片序列化器
    serializer_class = SKUSerializer
    # 分页
    pagination_class = PageNum

    # 重写get_queryset方法，根据前端是否传递keyword值返回不同查询结果
    def get_queryset(self):
        # 获取前端传递的keyword值
        keyword = self.request.query_params.get('keyword')
        # 如果keyword是空字符，则说明要获取所有用户数据
        if keyword is '' or keyword is None:
            return SKU.objects.all()
        else:
            # like=username__contains
            return SKU.objects.filter(name__contains=keyword)

    @action(methods=['get'], detail=False)
    def categories(self, request):
        """
        获取到三级分类
        :return:
        """
        data = GoodsCategory.objects.filter(subs__id=None)
        ser = GoodsCategorySerializer(data, many=True)
        return Response(ser.data)

    def specs(self, request, pk):
        """
        获取到spu商品的规格信息
        :param request:
        :param pk:  spu id
        :return:
        """
        # 查询对象
        spu = SPU.objects.get(id=pk)
        # 关联查询spu所有关联的规格信息
        data = spu.specs.all()
        # 序列化
        ser = SPUSpecSerializer(data, many=True)
        return Response(ser.data)
